package org.hk.kg.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hk.kg.TraceObject;
import org.hk.kg.exception.EleParserException;
import org.hk.kg.utils.Constants;
import org.hk.kg.utils.LocalResouce;
import org.hk.kg.utils.StringUtils;
import org.hk.kg.utils.XMLUtils;
import org.jdom.Document;
import org.jdom.Element;

public class KGMenu extends JMenuBar {
	private static Log logger = LogFactory.getLog(KGMenu.class);
	private static final long serialVersionUID = 8389102404971058081L;
	
	private static class KGMenuActionListener implements ActionListener
	{
		private String id;
		private String action;
		public KGMenuActionListener(String id,String action)
		{
			this.id = id;
			this.action = action;
		}
		public void actionPerformed(ActionEvent e) {
			if(id.equals(KGUiContext.current()))
			{
				return;
			}
			KGUiContext.instance.action(new TraceObject(id,action));
		}
	}

	public KGMenu()
	{
		super();
		_load_menus();
	}
	
	/**
	 *
	 */
	private void _load_menus()
	{
		InputStream ui_xml_ips = null;
		try {
			ui_xml_ips = LocalResouce.getConfigFile(Constants.UI_CONFIG);
			Document document = XMLUtils.getDocument(ui_xml_ips);
			Element menus_ele = XMLUtils.getElementFromDoc(document, Constants.UI_CONFIG_MENUS_TAG);
			for(Object menuTemp : menus_ele.getChildren())
			{
				Element menu = (Element) menuTemp;
				JMenu submenu = new JMenu(menu.getAttributeValue(Constants.UI_CONFIG_MENU_TXT_ATTR));
				this.add(submenu);
				loopConfig(menu,submenu);
			}
		} catch (Exception e) {
			logger.error(e);
		} 
		finally
		{
			try {
				ui_xml_ips.close();
			} catch (IOException e) {
				logger.error(e);
			}
		}
	}
	
	private void loopConfig(Element menu,JMenu parent)
	{
		List tempitems = menu.getChildren();
		for(Object itemTemp : tempitems)
		{
			Element itemElement = (Element) itemTemp;
			String text = itemElement.getAttributeValue(Constants.UI_CONFIG_MENU_TXT_ATTR),
				id = itemElement.getAttributeValue(Constants.UI_CONFIG_MENU_ID),
				action = itemElement.getAttributeValue(Constants.UI_CONFIG_MENU_ACTION);
			
			if(itemElement.getName().equals(Constants.UI_CONFIG_MENU_TAG))
			{
				JMenu subMenu = new JMenu(text);
				parent.add(subMenu);
				loopConfig(itemElement,subMenu);
			}
			else
			{
				JMenuItem item = new JMenuItem(text);
				if(!StringUtils.isEmpty(id))
				{
					item.setActionCommand(id);
					item.addActionListener(new KGMenuActionListener(id,action));
				}
				parent.add(item);
			}
		}
	}
}
